package com.yangxinxin.lesson.interceptor;

import com.yangxinxin.lesson.exception.BusinessException;
import com.yangxinxin.lesson.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

/** @Author yangxinxin
 * @Description //TODO
 * @Date 17:17 2020/2/21
 * @Param 
 * @return 
 **/
public class TokenInceptor implements HandlerInterceptor {
//1.拿到token 2.因为用户第一次登陆之后，下次请求系统的时候都会携带用户认证凭证3.凭证一般从head中或者cookies中拿取
    @Autowired
    private RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw  new BusinessException(4001002,"用户凭证不能为空！请重新登陆！");
        }else{
            if (!redisService.hasKey(token)){
                throw  new BusinessException(4001002,"用户凭证无效！请重新登陆！");
            }
            //通过token拿到用户Id
            String userId = (String) redisService.get(token);
            //是否存在                             token不等于
            if (redisService.hasKey(userId) && !token.equals(redisService.get(userId))){
                throw  new BusinessException(4001002,"您的账号已经在异地登陆，请重新登陆！");
            }
        }
        //放行
        return true;
    }
}
